package com.hwadee.ems.interceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.data.redis.core.StringRedisTemplate;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.bean.BeanUtil;

import lombok.RequiredArgsConstructor;

import com.hwadee.ems.util.UserHolder;
import com.hwadee.ems.domain.dto.UserDTO;
import static com.hwadee.ems.constant.RedisConstants.*;

@RequiredArgsConstructor
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate srt;

    @SuppressWarnings("null")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取请求头中的 token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            // 2. 不存在
            return true;
        }

        // 3. 基于 token 获取 redis 中的用户
        String key = LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = srt.opsForHash().entries(key);

        // 4. 判断用户是否存在
        if (userMap.isEmpty()) {
            // 5. 不存在
            return true;
        }

        // 6. 将查询到的 Hash 数据转为 UserDTO 对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        // 7. 存在，保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);

        // 8. 刷新 token 有效期
        srt.expire(key, LOGIN_USER_TTL, TimeUnit.MINUTES);

        // 9. 放行
        return true;
    }

}
